<template>
  <ErpLayout>
    <div class="modern-page">
      <!-- 页面头部 -->
      <div class="page-header">
        <div class="header-title">
          <h2 class="modern-text-gradient">用户管理</h2>
          <p class="header-description">管理系统用户信息，包括用户的创建、编辑、删除和角色分配等操作</p>
        </div>
        <div class="header-actions">
          <t-button theme="primary" @click="openCreateDialog">
            <template #icon>
              <component :is="'AddIcon'" />
            </template>
            新建用户
          </t-button>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <t-card class="search-card modern-card" :bordered="false">
        <t-form
          :model="searchParams"
          layout="inline"
          class="search-form"
          @submit="handleSearch"
          @reset="handleResetSearch"
        >
          <t-form-item label="关键词">
            <t-input
              v-model="searchParams.keyword"
              placeholder="搜索用户名/昵称/邮箱"
              clearable
              style="width: 200px"
            />
          </t-form-item>
          
          <t-form-item label="角色">
            <t-select
              v-model="searchParams.role"
              placeholder="请选择角色"
              clearable
              style="width: 150px"
            >
              <t-option value="admin" label="管理员" />
              <t-option value="user" label="普通用户" />
              <t-option value="operator" label="运营专员" />
              <t-option value="finance" label="财务专员" />
            </t-select>
          </t-form-item>
          
          <t-form-item label="状态">
            <t-select
              v-model="searchParams.status"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
            >
              <t-option value="active" label="正常" />
              <t-option value="inactive" label="禁用" />
            </t-select>
          </t-form-item>
          
          <t-form-item label="创建时间">
            <t-date-range-picker
              v-model="searchParams.dateRange"
              placeholder="请选择时间范围"
              clearable
              style="width: 240px"
            />
          </t-form-item>
          
          <t-form-item>
            <t-space>
              <t-button theme="primary" type="submit">搜索</t-button>
              <t-button type="reset">重置</t-button>
            </t-space>
          </t-form-item>
        </t-form>
      </t-card>

      <!-- 操作工具栏 -->
      <t-card class="toolbar-card modern-card" :bordered="false">
        <div class="toolbar">
          <div class="toolbar-left">
            <t-space>
              <t-button
                theme="danger"
                variant="outline"
                :disabled="!hasSelectedUsers"
                @click="handleBatchDelete"
              >
                <template #icon>
                  <component :is="'DeleteIcon'" />
                </template>
                批量删除
              </t-button>
              <t-button
                theme="default"
                variant="outline"
                :disabled="!hasSelectedUsers"
                @click="openRoleAssignDialog()"
              >
                <template #icon>
                  <component :is="'UserAddIcon'" />
                </template>
                批量分配角色
              </t-button>
            </t-space>
          </div>
          
          <div class="toolbar-right">
            <t-space>
              <span v-if="hasSelectedUsers" class="selected-info">
                已选择 {{ selectedCount }} 项
              </span>
              <t-button
                theme="default"
                variant="outline"
                @click="fetchUserList"
              >
                <template #icon>
                  <component :is="'RefreshIcon'" />
                </template>
                刷新
              </t-button>
            </t-space>
          </div>
        </div>
      </t-card>

      <!-- 用户列表 -->
      <t-card class="table-card modern-card" :bordered="false">
        <t-table
          ref="tableRef"
          :data="userList"
          :columns="columns"
          :loading="tableLoading"
          :pagination="pagination"
          row-key="id"
          :selected-row-keys="selectedRowKeys"
          stripe
          hover
          table-layout="auto"
          @page-change="handlePageChange"
          @select-change="handleSelectionChange"
        >
          <!-- 用户信息列 -->
          <template #user="{ row }">
            <div class="user-info">
              <t-avatar :size="32" :image="row.avatar">
                {{ (row.nickname || row.username || 'U').charAt(0).toUpperCase() }}
              </t-avatar>
              <div class="user-details">
                <div class="user-name">{{ row.nickname || row.username }}</div>
                <div class="user-email">{{ row.email }}</div>
              </div>
            </div>
          </template>
          
          <!-- 角色列 -->
          <template #roles="{ row }">
            <div class="roles-cell">
              <t-tag
                v-for="role in row.roles?.slice(0, 2)"
                :key="role.id"
                theme="primary"
                variant="light"
                size="small"
                class="role-tag"
              >
                {{ role.name }}
              </t-tag>
              <t-tag
                v-if="row.roles?.length > 2"
                theme="default"
                variant="outline"
                size="small"
                class="more-roles"
              >
                +{{ row.roles.length - 2 }}
              </t-tag>
            </div>
          </template>
          
          <!-- 状态列 -->
          <template #status="{ row }">
            <t-tag
              :theme="row.status === 'active' ? 'success' : 'danger'"
              variant="light"
            >
              {{ row.status === 'active' ? '正常' : '禁用' }}
            </t-tag>
          </template>
          
          <!-- 最后登录列 -->
          <template #lastLogin="{ row }">
            <div class="last-login">
              <div>{{ formatDate(row.lastLoginAt) || '从未登录' }}</div>
              <div v-if="row.lastLoginAt" class="login-info">
                登录{{ row.loginCount || 0 }}次
              </div>
            </div>
          </template>
          
          <!-- 操作列 -->
          <template #operation="{ row }">
            <t-space>
              <t-link theme="primary" @click="openUserDetail(row.id)">
                详情
              </t-link>
              <t-link theme="primary" @click="openEditDialog(row.id)">
                编辑
              </t-link>
              <t-dropdown
                :options="getActionOptions(row)"
                @click="(data) => handleActionClick(data, row)"
              >
                <t-link theme="primary">
                  更多
                  <component :is="'ChevronDownIcon'" size="14" />
                </t-link>
              </t-dropdown>
            </t-space>
          </template>
        </t-table>
      </t-card>

      <!-- 用户表单弹窗 -->
      <UserForm
        v-model:visible="dialogVisible"
        :user-data="currentUser"
        :mode="formMode"
        :loading="submitLoading"
        @submit="handleFormSubmit"
        @close="closeDialog"
      />

      <!-- 用户详情弹窗 -->
      <UserDetail
        v-model:visible="detailVisible"
        :user-data="currentUser"
        :loading="loading"
        @edit="handleDetailEdit"
        @close="closeDialog"
      />

      <!-- 角色分配弹窗 -->
      <UserRole
        v-model:visible="roleAssignVisible"
        :current-user="currentUser"
        :selected-users="selectedUsers"
        :loading="submitLoading"
        @submit="handleRoleAssign"
        @close="closeDialog"
      />
    </div>
  </ErpLayout>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import ErpLayout from '@/layouts/ErpLayout.vue'
import UserForm from './components/UserForm.vue'
import UserDetail from './components/UserDetail.vue'
import UserRole from './components/UserRole.vue'
import { useUserList } from './hooks/useUserList'

// 使用用户管理Hook
const {
  loading,
  tableLoading,
  submitLoading,
  userList,
  total,
  currentUser,
  pagination,
  searchParams,
  selectedRowKeys,
  selectedUsers,
  dialogVisible,
  detailVisible,
  roleAssignVisible,
  formMode,
  hasSelectedUsers,
  selectedCount,
  fetchUserList,
  handleCreateUser,
  handleUpdateUser,
  handleDeleteUser,
  handleBatchDelete,
  handleUpdateStatus,
  handleResetPassword,
  handleSearch,
  handleResetSearch,
  handlePageChange,
  handleSelectionChange,
  openCreateDialog,
  openEditDialog,
  openUserDetail,
  openRoleAssignDialog,
  handleRoleAssign,
  closeDialog
} = useUserList()

// 表格列配置
const columns = ref([
  {
    colKey: 'row-select',
    type: 'multiple',
    width: 50
  },
  {
    colKey: 'user',
    title: '用户信息',
    width: 220,
    fixed: 'left'
  },
  {
    colKey: 'phone',
    title: '手机号',
    width: 120
  },
  {
    colKey: 'roles',
    title: '角色',
    width: 180
  },
  {
    colKey: 'departmentName',
    title: '部门',
    width: 120
  },
  {
    colKey: 'status',
    title: '状态',
    width: 80
  },
  {
    colKey: 'lastLogin',
    title: '最后登录',
    width: 140
  },
  {
    colKey: 'createdAt',
    title: '创建时间',
    width: 140,
    cell: (h, { row }) => formatDate(row.createdAt)
  },
  {
    colKey: 'operation',
    title: '操作',
    width: 160,
    fixed: 'right'
  }
])

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

// 获取操作选项
const getActionOptions = (user) => {
  return [
    {
      content: '分配角色',
      value: 'assignRole'
    },
    {
      content: user.status === 'active' ? '禁用' : '启用',
      value: 'toggleStatus'
    },
    {
      content: '重置密码',
      value: 'resetPassword'
    },
    {
      content: '删除',
      value: 'delete',
      theme: 'error'
    }
  ]
}

// 处理操作点击
const handleActionClick = async (data, user) => {
  switch (data.value) {
    case 'assignRole':
      await openRoleAssignDialog(user.id)
      break
    case 'toggleStatus':
      const newStatus = user.status === 'active' ? 'inactive' : 'active'
      await handleUpdateStatus(user.id, newStatus, user.username)
      break
    case 'resetPassword':
      await handleResetPassword(user.id, user.username)
      break
    case 'delete':
      await handleDeleteUser(user.id, user.username)
      break
  }
}

// 处理表单提交
const handleFormSubmit = async (formData) => {
  let success = false
  
  if (formMode.value === 'create') {
    success = await handleCreateUser(formData)
  } else {
    success = await handleUpdateUser(currentUser.value.id, formData)
  }
  
  if (success) {
    closeDialog()
  }
}

// 处理详情编辑
const handleDetailEdit = (userData) => {
  detailVisible.value = false
  openEditDialog(userData.id)
}

// 处理角色分配 - 使用hook中的方法
// handleRoleAssign 已经在 useUserList hook 中定义
</script>

<style scoped>
/* 页面布局 */
.modern-page {
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.header-title h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.header-description {
  margin: 0;
  color: var(--td-text-color-secondary);
  font-size: 14px;
}

.header-actions {
  flex-shrink: 0;
}

/* 搜索表单 */
.search-card {
  border-radius: 12px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: flex-end;
}

/* 工具栏 */
.toolbar-card {
  border-radius: 12px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-info {
  color: var(--td-text-color-secondary);
  font-size: 14px;
}

/* 表格卡片 */
.table-card {
  border-radius: 12px;
  flex: 1;
}

/* 用户信息单元格 */
.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  flex: 1;
  min-width: 0;
}

.user-name {
  font-weight: 500;
  color: var(--td-text-color-primary);
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-email {
  font-size: 12px;
  color: var(--td-text-color-secondary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 角色单元格 */
.roles-cell {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.role-tag {
  border-radius: 4px;
}

.more-roles {
  border-radius: 4px;
  font-size: 12px;
}

/* 最后登录单元格 */
.last-login .login-info {
  font-size: 12px;
  color: var(--td-text-color-secondary);
  margin-top: 2px;
}

/* 表格样式增强 */
:deep(.t-table) {
  border-radius: 8px;
}

:deep(.t-table__header) {
  background: var(--td-bg-color-container);
}

:deep(.t-table__body tr:hover) {
  background: var(--td-bg-color-container-hover);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form {
    justify-content: flex-start;
  }
  
  .search-form :deep(.t-form-item) {
    margin-bottom: 16px;
  }
}

@media (max-width: 768px) {
  .modern-page {
    padding: 16px;
    gap: 16px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    align-self: flex-start;
  }
  
  .toolbar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .toolbar-left,
  .toolbar-right {
    justify-content: center;
  }
  
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form :deep(.t-form-item) {
    width: 100%;
  }
  
  .search-form :deep(.t-input),
  .search-form :deep(.t-select),
  .search-form :deep(.t-date-range-picker) {
    width: 100% !important;
  }
}

@media (max-width: 480px) {
  .user-info {
    gap: 8px;
  }
  
  .user-details {
    min-width: 0;
  }
  
  :deep(.t-table) {
    font-size: 12px;
  }
  
  :deep(.t-space) {
    flex-wrap: wrap;
  }
}
</style> 